package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"os"
	"strconv"
	"time"
)

var port = "8080"

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		d, err := httputil.DumpRequest(r, true)
		if err != nil {
			msg := fmt.Sprintf("couldn't dump request: %s", err)
			log.Println(msg)
			http.Error(w, msg, http.StatusInternalServerError)
			return
		}

		name, _ := os.Hostname()
		b := "Server: " + name + "\n" + "RemoteAddr: " + r.RemoteAddr + "\n" + string(d)

		log.Printf("request received:\n%s\n\n", b)

		if _, err := fmt.Fprint(w, b); err != nil {
			msg := fmt.Sprintf("couldn't write response: %s", err)
			log.Println(msg)
			http.Error(w, msg, http.StatusInternalServerError)
			return
		}
	})

	http.HandleFunc("/timeout", func(w http.ResponseWriter, r *http.Request) {
		v := r.URL.Query().Get("v")
		start := time.Now()

		s, err := strconv.Atoi(v)
		if err != nil {
			s = 15
		}
		time.Sleep(time.Duration(s) * time.Second)
		end := time.Now()
		fmt.Printf("StartTime: %s, EndTime: %s, v: %s\n", start.Format("2006-01-02 15:04:05"), end.Format("2006-01-02 15:04:05"), v)
		fmt.Fprint(w, "OK")
	})

	if p := os.Getenv("PORT"); p != "" {
		port = p
	}

	addr := ":" + port

	log.Printf("http-dump is listening at %s\n", addr)
	log.Fatal(http.ListenAndServe(addr, nil))

}
